package com.trytech.mongoocrawler.server.common.queue;

import com.lmax.disruptor.WorkHandler;
import com.trytech.mongoocrawler.common.UrlUtil;
import com.trytech.mongoocrawler.server.entity.LianjiaItem;
import com.trytech.mongoocrawler.server.parser.HtmlParser;
import com.trytech.mongoocrawler.server.transport.http.WebResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.MalformedURLException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by hp on 2017-1-25.
 */
@Slf4j
public class WebResultFetcherWorkHandler extends FetcherWorkHandler implements WorkHandler<WebResultFetcherEvent> {

    private static ConcurrentHashMap<String, HtmlParser> parserMap = new ConcurrentHashMap<String, HtmlParser>();
    private UrlFetcherEventProducer urlFetcherEventProducer;

    public WebResultFetcherWorkHandler(DisruptorContext disruptorContext){
        super(disruptorContext);
        this.urlFetcherEventProducer =  new UrlFetcherEventProducer(disruptorContext.getUrlResultRingBuffer());
    }

    @Override
    public void onEvent(WebResultFetcherEvent webResultFetcherEvent) throws Exception {
        WebResult<String> webResult = webResultFetcherEvent.getData();
        System.out.println("收到了消息");
        if(webResult != null) {
            String html = ((WebResult<String>)webResult).getData();
            if(StringUtils.isNotEmpty(html)){
//                    List<LianjiaItem> itemList = LianjiaHtmlParser.parse(html);
//                    for(LianjiaItem item : itemList){
//                        String sql = "insert into lj_house(`C_TITLE`,`C_LOCATION`,`C_TYPE`,`C_FLOORSPACE`,`C_PRICE`,`C_UNIT_PRICE`) values('" + item.getTitle() + "','" + item.getLocation() + "','"+item.getType()+
//                                "','"+item.getFloorSpace()+"',"+item.getPrice().toString()+","+item.getUnitPrice().toString()+")";
//                        MySQLUtils.insert(sql);
//                    }
                HtmlParser parser = webResult.getParser();
                Object result = parser.parse(webResult, this.urlFetcherEventProducer);
                if (result instanceof LianjiaItem || result instanceof List) {
                        try {
                            List<LianjiaItem> itemList = (List<LianjiaItem>) result;
                            disruptorContext.getCrawlerSession().getSessionConfig().getPipeline().store(itemList);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
            }
        }
    }

    public void registerParser(String url, HtmlParser htmlParser) {
        try {
            parserMap.put(UrlUtil.filterDomainAndPath(url), htmlParser);
        } catch (MalformedURLException e) {
            log.info("非法url:{}", url);
        }
    }
}
